
#import "PushSettingsViewController.h"
#import "AppDelegate.h"

@implementation PushSettingsViewController

//
// push config
//
@synthesize pushConfig														= _pushConfig;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super initWithStyle:UITableViewStyleGrouped];
	if(!self)
		return nil;
	
	//
	// load setting
	//
	self.pushConfig															= [DataCenter sharedDataCenter].pushConfig;
	
	//
	// setup title
	//
	self.title																= NSLocalizedStringFromTable(@"Push Settings", @"PushSettingsViewController", nil);
	self.navigationItem.rightBarButtonItem									= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveSettings:)] autorelease];
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.pushConfig															= nil;
	
	[super dealloc];
}

//
// get section count
//
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
	return 3;
}

//
// get title
//
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
	if(!section)
		return NSLocalizedStringFromTable(@"APN Provider Address", @"PushSettingsViewController", nil);
	
	if(section == 1)
		return NSLocalizedStringFromTable(@"Enable Push By Category", @"PushSettingsViewController", nil);
	
	return nil;
}

//
// get footer
//
- (NSString*)tableView:(UITableView*)tableView titleForFooterInSection:(NSInteger)section
{
	if(section)
		return nil;
	
	NSString* format														= NSLocalizedStringFromTable(@"aps-environment:%@\ndevice token:\n%@\n", @"PushSettingsViewController", nil);
	AppDelegate* delegate													= (AppDelegate*)[[UIApplication sharedApplication] delegate];
	return [NSString stringWithFormat:format, [delegate.entitlements objectForKey:@"aps-environment"], delegate.deviceToken];
}

//
// get row count
//
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return section == 0 ? 1 : (section == 1 ? self.pushConfig.categoryFilter.count : 2);
}

//
// get cell
//
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	if(!indexPath.section)
	{
		UITableViewCell* theCell											= [tableView dequeueReusableCellWithIdentifier:@"v1"];
		if(!theCell)
			theCell															= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"v1"] autorelease];
		
		UITextField* textField												= [[[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 21)] autorelease];
		theCell.textLabel.text												= NSLocalizedStringFromTable(@"Address", @"PushSettingsViewController", nil);
		textField.placeholder												= NSLocalizedStringFromTable(@"server address", @"PushSettingsViewController", nil);
		textField.text														= self.pushConfig.apnProvider;
		textField.tag														= 0;
		textField.keyboardType												= UIKeyboardTypeURL;
		textField.returnKeyType												= UIReturnKeyDone;
		
		textField.adjustsFontSizeToFitWidth									= YES;
		textField.autocorrectionType										= UITextAutocorrectionTypeNo;
		textField.autocapitalizationType									= UITextAutocapitalizationTypeNone;
		textField.clearButtonMode											= UITextFieldViewModeWhileEditing;
		textField.delegate													= self;
		theCell.accessoryView												= textField;
		theCell.selectionStyle												= UITableViewCellSelectionStyleNone;
		theCell.accessoryType												= UITableViewCellAccessoryNone;
		return theCell;
	}
	else if(indexPath.section == 1)
	{
		UITableViewCell* theCell											= [tableView dequeueReusableCellWithIdentifier:@"ds"];
		if(!theCell)
			theCell															= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ds"] autorelease];
		
		theCell.textLabel.text												= [[self.pushConfig.categoryFilter objectAtIndex:indexPath.row] valueForKey:@"name"];
		UISwitch* switchView												= [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
		[switchView setOn:[[[self.pushConfig.categoryFilter objectAtIndex:indexPath.row] valueForKey:@"enabled"] boolValue] animated:NO];
		[switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
		switchView.tag														= indexPath.row;
		theCell.accessoryView												= switchView;
		theCell.accessoryType												= UITableViewCellAccessoryNone;
		theCell.selectionStyle												= UITableViewCellSelectionStyleNone;
		return theCell;
	}
	
	UITableViewCell* theCell												= [tableView dequeueReusableCellWithIdentifier:@"d"];
	if(!theCell)
		theCell																= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"d"] autorelease];
	
	if(indexPath.row)
		theCell.textLabel.text												= NSLocalizedStringFromTable(@"Copy Device Token", @"PushSettingsViewController", nil);
	else
		theCell.textLabel.text												= NSLocalizedStringFromTable(@"Restore Default Settings", @"PushSettingsViewController", nil);
	
	theCell.accessoryType													= UITableViewCellAccessoryNone;
	theCell.textLabel.textAlignment											= UITextAlignmentCenter;
	return theCell;
}

//
// select row
//
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	if(!indexPath.section)
	{
		UITableViewCell* theCell											= [tableView cellForRowAtIndexPath:indexPath];
		[theCell.accessoryView becomeFirstResponder];
	}
	else if(indexPath.section == 2)
	{
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		
		if(indexPath.row == 0)
		{
			NSString* title													= NSLocalizedString(@"Confirm", nil);
			NSString* message												= NSLocalizedStringFromTable(@"Are you sure want to restore default settings?", @"PushSettingsViewController", nil);
			id onDismiss = ^void(int buttonIndex)
			{
				self.pushConfig												= [[DataCenter sharedDataCenter] defaultPushConfig];
				[tableView reloadData];
			};
			[tableView deselectRowAtIndexPath:indexPath animated:YES];
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"Cancel", nil) others:[NSArray arrayWithObjects:NSLocalizedString(@"OK", nil), nil] onDismiss:onDismiss onCancel:nil];
		}
		else
		{
			[[UIPasteboard generalPasteboard] setString:[(AppDelegate*)[[UIApplication sharedApplication] delegate] deviceToken]];
		}
	}
}

//
// end editing
//
- (void)textFieldDidEndEditing:(UITextField*)textField
{
	self.pushConfig.apnProvider												= textField.text;
}

//
// return
//
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{	
	[self.tableView endEditing:YES];
	return YES;
}

//
// switch changed
//
- (void)switchChanged:(id)sender
{
	NSMutableDictionary* config												= [self.pushConfig.categoryFilter objectAtIndex:[sender tag]];
	[config setValue:[NSNumber numberWithBool:[sender isOn]] forKey:@"enabled"];
}

//
// save settings
//
- (void)saveSettings:(id)sender
{
	[self.tableView endEditing:YES];
	if(!self.pushConfig.apnProvider.length)
		return (void)[UIAlertView alertViewWithTitle:NSLocalizedString(@"Error", nil) message:NSLocalizedStringFromTable(@"Please input APN Provider address", @"PushSettingsViewController", nil) cancel:NSLocalizedString(@"OK", nil)];
	
	DataCenter* dataCenter													= [DataCenter sharedDataCenter];
	AppDelegate* appDelegate												= [UIApplication sharedApplication].delegate;
	dataCenter.pushConfig													= self.pushConfig;
	[dataCenter savePushConfig];
	if(!appDelegate.deviceToken.length)
	{
		[self.navigationController popViewControllerAnimated:YES];
		return;
	}
	
	id uploadCategoryFilterCallback = ^void(AsyncHttpRequest* uploadCategoryFilterRequest)
	{
		[ActivityView removeView];
		if(uploadCategoryFilterRequest.error)
		{
			NSString* message												= [uploadCategoryFilterRequest errorDescription];
			NSString* title													= NSLocalizedStringFromTable(@"Upload Category Filter Failed", @"PushSettingsViewController", nil);
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
		}
		else
		{
			id onCancel = ^void()
			{
				[self.navigationController popViewControllerAnimated:YES];
			};
			NSString* title													= NSLocalizedStringFromTable(@"Upload Category Finished", @"PushSettingsViewController", nil);
			NSString* message												= NSLocalizedStringFromTable(@"Category filter has been uploaded to APN provider", @"PushSettingsViewController", nil);
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil) others:nil onDismiss:nil onCancel:onCancel];
		}
	};
	[ActivityView showActivityView:NSLocalizedStringFromTable(@"Uploading Category Filter", @"PushSettingsViewController", nil) networking:YES];
	[appDelegate uploadCategoryFilterWithCallback:uploadCategoryFilterCallback];
}

@end